package mqtt

import (
	"fmt"
	"goweb/db"
	"goweb/route"
	"time"

	mqtt "github.com/eclipse/paho.mqtt.golang"
)

func Tsos() {
	opts := mqtt.NewClientOptions()
	opts.AddBroker("mqtt://localhost:1883")
	opts.SetClientID("go_mqtt_client")
	opts.SetUsername("wlw")
	opts.SetPassword("wlw")
	opts.SetDefaultPublishHandler(func(client mqtt.Client, msg mqtt.Message) {
		fmt.Println("Received message from topic:", msg.Topic(), "Message:", string(msg.Payload()))
		var m db.Msg
		m.Msg = string(msg.Payload())
		m.Name = "system"
		m.Time = time.Now().Format("2006-01-02 15:04:05.000")
		route.Msg_chan <- m
		db.Changes_channel <- db.Info_Json{Online: 0, Offline: 0, Warning: 1, Notification: 0, AI: 0, LostNum: 0,TextToSpeech:0,LoginNum:0}
		db.Insert_msg(m)
	})
	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	topic := "tsos" // 替换为你想要监听的主题
	if token := client.Subscribe(topic, 0, nil); token.Wait() && token.Error() != nil {
		panic(token.Error())
	}
	fmt.Println("Subscribed to topic:", topic)
	select {}
}
